<?php


namespace app\api\validate;


use app\common\controller\LockService;
use app\common\model\AppConfig;
use app\common\model\OrderLog;
use app\lib\exception\ParamException;
use app\lib\exception\TokenErrorException;
use think\Log;
use think\Validate;

class TokenValidate extends Validate
{

    /**ascii码从小到大排序，并加密
     * @param array $params
     * @return bool|string
     */

    public function checkToken($param)
    {
		//return true;
        $token = $param['token'];
        unset($param['token']);
        //将参数数组key按照自然排序
        $arr_keys = array_keys($param);
        asort($arr_keys);
        //将排序后的参数数组按照key=val&key=val的形式组成字符串，将字符串与secretKey连接
        $sb = '';
        foreach($arr_keys as $key=>$val){
            $sb .= $val . '=' . $param[$val] . '&';
        }

        // 查询缓存得到api_key
        $redis = (new LockService())::getRedisConn();

        $redis_info = $redis->get('apiKey:'.$param['org_id'].':'.$param['app_id']);

        if(!$redis_info){
            $app = model('AppConfig')->getInfoByMap(['org_id'=>$param['org_id'],'id'=>$param['app_id']],false,'',false);

            if(!$app){
                OrderLog::record('',"应用不存在",$param);
                $e = new ParamException(['code'=>400,'msg'=>'应用不存在','errorCode'=>10004]);throw $e;
            }
            $status = $app['status'];
            if($status != 1){
                OrderLog::record('',"应用未授权",$param);
                $e = new ParamException(['code'=>400,'msg'=>'应用未授权','errorCode'=>10005]);throw $e;
            }
            $redis->set('apiKey:'.$param['org_id'].':'.$param['org_id'],json_encode($app));
            $apiKey = $app['api_key'];
        }else{
            $status = json_decode($redis_info,true)['status'];
            if($status != 1){
                OrderLog::record('',"应用未授权",$param);
                $e = new ParamException(['code'=>400,'msg'=>'应用未授权','errorCode'=>10005]);throw $e;
            }
            $apiKey = json_decode($redis_info,true)['api_key'];
        }


        $sb .= 'apiKey='.$apiKey;

        $sign = md5($sb);

        if($sign != $token){
            OrderLog::record('',"上报签名：".$token.'--'."验证签名：".$sign,$param);
            $e = new TokenErrorException();throw $e;
        }else{
            return true;
        }
    }
}